package com.mgface.metadata.design.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project mddesign
 * @create 2021-07-26 11:26
 **/
public final class SnowFlakeUtil {
    private long machineId;
    private long dataCenterId;
    private Snowflake snowflake;

    private Snowflake getSnowflake() {
        return snowflake;
    }

    /**
     * 初始化构造，无参构造有参函数，默认节点都是0
     */
    public SnowFlakeUtil() {
        this(0L, 0L);
    }

    public SnowFlakeUtil(long machineId, long dataCenterId) {
        this.machineId = machineId;
        this.dataCenterId = dataCenterId;
        this.snowflake = IdUtil.createSnowflake(machineId, dataCenterId);
    }

    /**
     * 成员类，SnowFlakeUtil的实例对象的保存域
     */
    private static class IdGenHolder {
        private static final SnowFlakeUtil instance = new SnowFlakeUtil();
    }

    /**
     * 外部调用获取SnowFlakeUtil的实例对象，确保不可变
     */
    private static SnowFlakeUtil get() {
        return IdGenHolder.instance;
    }


    public static String getId() {
        return String.valueOf(SnowFlakeUtil.get().getSnowflake().nextId());
    }

}
